package com.niubi.yygh.msm.service.impl;


import com.niubi.yygh.msm.service.MsmService;
import com.niubi.yygh.vo.msm.MsmVo;
import org.apache.http.HttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.HttpUtils;
import util.RandomUtil;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {


  @Override
  public boolean sendDx(String phone, String code) {
    String host = "http://dingxin.market.alicloudapi.com";
    String path = "/dx/sendSms";
    String method = "POST";
    String appcode = "e3df5e294dac481b8a851c7547f9e13e";
    //String appcode = "83359fd73fe94948385f570e3c139105";
    Map<String, String> headers = new HashMap<>();
    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    headers.put("Authorization", "APPCODE " + appcode);
    Map<String, String> querys = new HashMap<String, String>();
    querys.put("mobile", phone);
    querys.put("param", "code:" + code);
    querys.put("tpl_id", "TP1711063");
    Map<String, String> bodys = new HashMap<String, String>();
    try {
      /**
       * 重要提示如下:
       * HttpUtils请从
       * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
       * 下载
       *
       * 相应的依赖请参照
       * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
       */
      HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
      System.out.println(response.toString());
      //获取response的body
      //System.out.println(EntityUtils.toString(response.getEntity()));
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  @Override
  public boolean send(MsmVo msmVo) {
    if(!StringUtils.isEmpty(msmVo.getPhone())) {
      //String code = (String)msmVo.getParam().get("code");
      //仅为了测试
      String code = RandomUtil.getFourBitRandom();
      return this.sendDx(msmVo.getPhone(),code);
    }
    return false;
  }
}



